package serice

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"user-srv/basic/inits"
	__ "user-srv/basic/proto"
	"user-srv/handler/model"
	"user-srv/pkg"
)

type Server struct {
	__.UnimplementedUserGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	get := inits.Rdb.Get(inits.Ctx, "Send")
	if get.Val() <= "1" {
		return nil, fmt.Errorf("60秒只能发送一次")
	}
	code := rand.Intn(9000) + 1000
	send, _ := pkg.Send(in.Phone, strconv.Itoa(code))
	if *send.Body.Code != "OK" {
		return nil, fmt.Errorf(*send.Body.Message)
	}

	inits.Rdb.Set(inits.Ctx, "SendSms", code, time.Minute*2)
	inits.Rdb.Incr(inits.Ctx, "Send")
	inits.Rdb.Expire(inits.Ctx, "Send", time.Second*60)
	return &__.SendSmsResp{}, nil
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user model.User

	if user.Username != in.Username {
		user.Username = in.Username
		user.Password = in.Password
		user.Phone = in.Phone
		inits.DB.Where("username=?", in.Username).Find(&user)
	} else {
		get := inits.Rdb.Get(inits.Ctx, "SendSms")
		if get.Val() != in.Phone {
			return nil, fmt.Errorf("短信错误")
		}
		if user.Password != in.Password {
			return nil, fmt.Errorf("密码错误")
		}
		inits.DB.Debug().Create(&user)
	}
	return &__.LoginResp{}, nil
}
func (s *Server) Add(_ context.Context, in *__.AddReq) (*__.AddResp, error) {
	var video model.Video
	if video.Content != in.Content {
		return nil, fmt.Errorf("视频不存在")
	}
	inits.DB.Debug().Create(&video)
	return &__.AddResp{
		Id: int64(video.ID),
	}, nil
}
